<template>
  <div>
    <el-card class="qianming-container" body-style="padding:0px">
      <vue-esign
          ref="esign"
          :isCrop="isCrop"
          :width="600"
          :height="300"
          :lineWidth="lineWidth"
          :lineColor="lineColor"
          :format="'image/png'"
          :bgColor.sync="bgColor"
      ></vue-esign>
      <div class="contro-container">
        <el-button type="danger" @click="handleReset">清空画板</el-button>
        <el-button type="primary" @click="handleGenerate">确认签名</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import vueEsign from "vue-esign";
export default {
  components: { vueEsign },
  name: "Qianming",
  data() {
    return {
      lineWidth: 6,
      lineColor: "#000000",
      bgColor: "",
      resultImg: "",
      isCrop: false,
    };
  },
  methods: {
    //清空画板..
    handleReset() {
      this.$refs.esign.reset();
      this.resultImg = "";
    },
    //生成签名图片..
    handleGenerate() {
      this.$refs["esign"].generate().then((res) => {
        this.resultImg = res; // 得到了签字生成的base64图片
        this.$emit("setsign",res)
        //将res传给父组件
        // 也可以转换成在线地址
        //this.dataURLtoFile(res)

      }).catch((err) => {
        //  没有签名，点击生成图片时调用
        this.$message({
          message: err + " 未签名！",
          type: "warning",
        });
      });
    },

    //将base64 上传到服务器，转换成在线地址
    dataURLtoFile(res) {
      const file = this.dataURItoBlob(res)
      let formData = new FormData()
      formData.append("file",file);
      // 上传图片
      uploadFile(formData).then(result=>{
        this.$emit("setsignin",result.data)
      })
    },
    dataURItoBlob(base64Data) {
      var byteString;
      if(base64Data.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(base64Data.split(',')[1]);
      else{
        byteString = unescape(base64Data.split(',')[1]);
      }
      var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
      var ia = new Uint8Array(byteString.length);
      for(var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      var blob = new Blob([ia], {
        type: mimeString
      });
      return blob;
    },
  },
};
</script>

<style scoped>
button {
  height: 40px;
}
.contro-container {
  width: 600px;
  height: 50px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  background-color: #d3d3d3;
  position: absolute;
  bottom: 0px;
}
.qianming-container {
  width: 600px;
  height: 350px;
  margin: 10px auto;
  position: relative;
}
.text {
  font-size: 14px;
}
.item {
  margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.box-card {
  width: 95%;
  margin-left: 2.5%;
  margin-top: 20px;
}
</style>
